using System;
using System.Data;
using System.Data.SqlClient;
using System.Windows.Forms;
using Syncfusion.Windows.Forms.Grid;
using ctsu.Data;


namespace ctsu.Admin.Forms.CoreLab
{
	public class SelectLocationDlg : System.Windows.Forms.Form
	{
		public delegate void SelectLocationEventHandler(object sender, SelectLocationEventArgs e);
		public event SelectLocationEventHandler SelectLocationEvent;
		private int _test;
		private int _protocol;
		private string _formName;
		private bool _isInit = true;

		#region controls
		private System.Windows.Forms.Label label1;
		private System.Windows.Forms.Label label2;
		private System.Windows.Forms.ComboBox cboTest;
		private System.Windows.Forms.ComboBox cboProtocol;
		private System.ComponentModel.Container components = null;
		private System.Windows.Forms.Label label3;
		private System.Windows.Forms.Button btnGet;
		private Syncfusion.Windows.Forms.Grid.GridControl dg;
		private System.Windows.Forms.CheckBox chkKeepOpen;
		private System.Windows.Forms.Button btnClose;
		private System.Windows.Forms.Button btnReturn;
		private System.Windows.Forms.Button btnShow;
		private GridControl _grid;
		#endregion controls

		public SelectLocationDlg(string test, int protocol, GridControl grid, string formName)
		{
			_formName = formName;
			if (test.Length > 0)
				_test = this.GetTestID(test);
			_protocol = protocol;
			_grid = grid;
			InitializeComponent();
			_grid.SelectionChanged += new GridSelectionChangedEventHandler(_grid_SelectionChanged);
			InitializeGrid();
		}

		private void InitializeGrid()
		{
			dg[0, 1].Text = "Location";
			dg[0, 2].Text = "Count";
			dg.ColWidths[1] = 125;
			dg.ColWidths[2] = 50;
		}

		protected override void Dispose(bool disposing)
		{
			if (disposing)
			{
				if (components != null)
				{
					components.Dispose();
				}
			}
			base.Dispose(disposing);
		}

		#region Windows Form Designer generated code
		/// <summary>
		/// Required method for Designer support - do not modify
		/// the contents of this method with the code editor.
		/// </summary>
		private void InitializeComponent()
		{
			this.label1 = new System.Windows.Forms.Label();
			this.cboTest = new System.Windows.Forms.ComboBox();
			this.label2 = new System.Windows.Forms.Label();
			this.cboProtocol = new System.Windows.Forms.ComboBox();
			this.label3 = new System.Windows.Forms.Label();
			this.btnGet = new System.Windows.Forms.Button();
			this.dg = new Syncfusion.Windows.Forms.Grid.GridControl();
			this.chkKeepOpen = new System.Windows.Forms.CheckBox();
			this.btnClose = new System.Windows.Forms.Button();
			this.btnReturn = new System.Windows.Forms.Button();
			this.btnShow = new System.Windows.Forms.Button();
			((System.ComponentModel.ISupportInitialize)(this.dg)).BeginInit();
			this.SuspendLayout();
			// 
			// label1
			// 
			this.label1.Location = new System.Drawing.Point(8, 8);
			this.label1.Name = "label1";
			this.label1.Size = new System.Drawing.Size(32, 16);
			this.label1.TabIndex = 0;
			this.label1.Text = "Test:";
			// 
			// cboTest
			// 
			this.cboTest.Location = new System.Drawing.Point(56, 8);
			this.cboTest.Name = "cboTest";
			this.cboTest.Size = new System.Drawing.Size(144, 21);
			this.cboTest.TabIndex = 1;
			this.cboTest.SelectedIndexChanged += new System.EventHandler(this.cboTest_SelectedIndexChanged);
			// 
			// label2
			// 
			this.label2.Location = new System.Drawing.Point(8, 40);
			this.label2.Name = "label2";
			this.label2.Size = new System.Drawing.Size(40, 16);
			this.label2.TabIndex = 2;
			this.label2.Text = "Protool:";
			// 
			// cboProtocol
			// 
			this.cboProtocol.Location = new System.Drawing.Point(56, 40);
			this.cboProtocol.Name = "cboProtocol";
			this.cboProtocol.Size = new System.Drawing.Size(144, 21);
			this.cboProtocol.TabIndex = 3;
			this.cboProtocol.SelectedIndexChanged += new System.EventHandler(this.cboProtocol_SelectedIndexChanged);
			// 
			// label3
			// 
			this.label3.Location = new System.Drawing.Point(8, 72);
			this.label3.Name = "label3";
			this.label3.Size = new System.Drawing.Size(56, 16);
			this.label3.TabIndex = 5;
			this.label3.Text = "Locations";
			// 
			// btnGet
			// 
			this.btnGet.Location = new System.Drawing.Point(208, 40);
			this.btnGet.Name = "btnGet";
			this.btnGet.Size = new System.Drawing.Size(88, 23);
			this.btnGet.TabIndex = 6;
			this.btnGet.Text = "Get Locations";
			this.btnGet.Click += new System.EventHandler(this.btnGet_Click);
			// 
			// dg
			// 
			this.dg.BorderStyle = System.Windows.Forms.BorderStyle.FixedSingle;
			this.dg.ColCount = 2;
			this.dg.Location = new System.Drawing.Point(8, 88);
			this.dg.Name = "dg";
			this.dg.NumberedColHeaders = false;
			this.dg.NumberedRowHeaders = false;
			this.dg.RowCount = 0;
			this.dg.Size = new System.Drawing.Size(288, 144);
			this.dg.SmartSizeBox = false;
			this.dg.TabIndex = 7;
			this.dg.Text = "gridControl1";
			// 
			// chkKeepOpen
			// 
			this.chkKeepOpen.Location = new System.Drawing.Point(8, 240);
			this.chkKeepOpen.Name = "chkKeepOpen";
			this.chkKeepOpen.Size = new System.Drawing.Size(120, 16);
			this.chkKeepOpen.TabIndex = 8;
			this.chkKeepOpen.Text = "Keep window open ";
			// 
			// btnClose
			// 
			this.btnClose.Location = new System.Drawing.Point(221, 272);
			this.btnClose.Name = "btnClose";
			this.btnClose.TabIndex = 9;
			this.btnClose.Text = "Close";
			this.btnClose.Click += new System.EventHandler(this.btnClose_Click);
			// 
			// btnReturn
			// 
			this.btnReturn.Location = new System.Drawing.Point(8, 272);
			this.btnReturn.Name = "btnReturn";
			this.btnReturn.Size = new System.Drawing.Size(96, 23);
			this.btnReturn.TabIndex = 10;
			this.btnReturn.Text = "Return Location";
			this.btnReturn.Click += new System.EventHandler(this.btnReturn_Click);
			// 
			// btnShow
			// 
			this.btnShow.Location = new System.Drawing.Point(128, 240);
			this.btnShow.Name = "btnShow";
			this.btnShow.Size = new System.Drawing.Size(168, 23);
			this.btnShow.TabIndex = 11;
			this.btnShow.Text = "Show selected contents...";
			this.btnShow.Click += new System.EventHandler(this.btnShow_Click);
			// 
			// SelectLocationDlg
			// 
			this.AutoScaleBaseSize = new System.Drawing.Size(5, 13);
			this.ClientSize = new System.Drawing.Size(304, 302);
			this.Controls.Add(this.btnShow);
			this.Controls.Add(this.btnReturn);
			this.Controls.Add(this.btnClose);
			this.Controls.Add(this.chkKeepOpen);
			this.Controls.Add(this.dg);
			this.Controls.Add(this.btnGet);
			this.Controls.Add(this.label3);
			this.Controls.Add(this.cboProtocol);
			this.Controls.Add(this.label2);
			this.Controls.Add(this.cboTest);
			this.Controls.Add(this.label1);
			this.Name = "SelectLocationDlg";
			this.Text = "Select Location";
			this.Load += new System.EventHandler(this.SelectLocationDlg_Load);
			((System.ComponentModel.ISupportInitialize)(this.dg)).EndInit();
			this.ResumeLayout(false);

		}
		#endregion

		private void SelectLocationDlg_Load(object sender, System.EventArgs e)
		{
			FillCombos();
			if (_test > 0)
				cboTest.SelectedValue = _test;
			if (_protocol > 0)
				cboProtocol.SelectedValue = _protocol;

			GetLocations();
			this.Text += " - " + _formName;

			_isInit = false;
		}

		private void GetLocations()
		{
			dg.RowCount = 0;
			string sql = "SELECT DISTINCT t.Location " +
				"FROM TestSamples t INNER JOIN DrawSamples d ON t.DrawSample = d.ID " +
				"WHERE (t.TestType = @TestType) AND (d.Protocol = @Protocol) AND LEN(t.Location) > 0 AND t.Location IS NOT NULL";

			//SqlConnection conn = LoginForm.GetSqlConnection();
			try
			{
				SqlParameter[] paras = new SqlParameter[2];
				paras[0] = new SqlParameter("@TestType", _test);
				paras[1] = new SqlParameter("@Protocol", _protocol);

				DataSet ds = DataAccess.GetDataSet(sql, paras);
				dg.RowCount = ds.Tables[0].Rows.Count;
				if (dg.RowCount == 0)
				{
					MessageBox.Show("There are no locations for this criteria.");
					return;
				}
				int row = 1;
				string location;
				foreach (DataRow dr in ds.Tables[0].Rows)
				{
					location = dr[0].ToString();
					dg[row, 1].Text = dr[0].ToString();
					dg[row, 2].Text = GetLocationCount(location);
					row++;
				}


			}
			catch
			{
				throw;
			}
			finally
			{
				//if(conn != null)
				//    conn.Dispose();				
			}
		}

		private string GetLocationCount(string location)
		{
			string sql = "SELECT COUNT(*) FROM TestSamples WHERE Location ='" + location + "'";
			//SqlConnection conn = LoginForm.GetSqlConnection();
			try
			{
				int count = (int)DataAccess.GetScalarObject(CommandType.Text, sql);
				return count.ToString();
			}
			catch
			{
				throw;
			}
			finally
			{
				//if(conn != null)
				//    conn.Dispose();				
			}
		}

		private int GetTestID(string test)
		{
			string sql = "SELECT ID FROM TestType_L WHERE Display='" + test + "'";
			//SqlConnection conn = LoginForm.GetSqlConnection();
			try
			{
				return (int)DataAccess.GetScalarObject(CommandType.Text, sql);
			}
			catch
			{
				throw;
			}
			finally
			{
				//if(conn != null)
				//    conn.Dispose();				
			}
		}

		private void FillCombos()
		{
			string sql = "SELECT ID, Display FROM TestType_L " +
				" ORDER BY Display";

			//SqlConnection conn = LoginForm.GetSqlConnection();
			DataTable dt = null;

			try
			{
				DataSet ds = DataAccess.GetDataSet(sql);
				dt = ds.Tables[0];

				cboTest.BeginUpdate();
				cboTest.DataSource = dt;
				cboTest.DisplayMember = "Display";
				cboTest.ValueMember = "ID";
				cboTest.EndUpdate();
				cboTest.SelectedIndex = -1;

				sql = "SELECT ID, ProtocolNumber FROM Protocol " +
					"ORDER BY ProtocolNumber";

				ds = DataAccess.GetDataSet(sql);
				dt = ds.Tables[0];

				cboProtocol.BeginUpdate();
				cboProtocol.DataSource = dt;
				cboProtocol.DisplayMember = "ProtocolNumber";
				cboProtocol.ValueMember = "ID";
				cboProtocol.EndUpdate();
				cboProtocol.SelectedIndex = -1;

			}
			catch
			{
				throw;
			}
			finally
			{
				//if(conn != null)
				//    conn.Dispose();				
			}

		}

		private void _grid_SelectionChanged(object sender, GridSelectionChangedEventArgs e)
		{
			try
			{
				int row = e.Range.Top;
				Console.WriteLine("row: " + row);
				if (row == 0)
					return;

				if (_formName == "Samples Check-In" || _formName == "Samples Change Location")
				{
					_test = GetTestID(_grid[row, 5].FormattedText);
					cboTest.SelectedValue = _test;
					_protocol = int.Parse(_grid[row, 3].Text);
					cboProtocol.SelectedValue = _protocol;
				}
				if (_formName == "Legacy Labels")
				{
					_test = GetTestID(_grid[row, 6].FormattedText);
					cboTest.SelectedValue = _test;
					_protocol = int.Parse(_grid[row, 3].Text);
					cboProtocol.SelectedValue = _protocol;
				}
				if (_formName == "New Samples From Existing - In")
				{
					string test = _grid[row, 6].FormattedText;
					if (test.Length == 0)
					{
						_test = 0;
						cboTest.SelectedIndex = -1;
					}
					else
					{
						_test = GetTestID(test);
						cboTest.SelectedValue = _test;
					}
					_protocol = int.Parse(_grid[row, 4].Text);
					cboProtocol.SelectedValue = _protocol;
				}
				GetLocations();
			}
			catch (Exception ex)
			{
				Console.WriteLine(ex.Message);
			}
		}

		private void btnClose_Click(object sender, System.EventArgs e)
		{
			_grid.SelectionChanged -= new GridSelectionChangedEventHandler(_grid_SelectionChanged);
			_grid = null;
			this.Close();
		}

		private void btnReturn_Click(object sender, System.EventArgs e)
		{
			GridRangeInfoList list = dg.Selections.GetSelectedRows(true, false);
			if (list.Count == 0)
				return;

			GridRangeInfo range = list[0];
			int row = range.Top;
			string location = dg[row, 1].Text;

			SelectLocationEventArgs ea = new SelectLocationEventArgs();
			ea.Location = location;

			if (SelectLocationEvent != null)
				SelectLocationEvent(this, ea);

			if (!chkKeepOpen.Checked)
				this.Close();
		}

		private void btnShow_Click(object sender, System.EventArgs e)
		{
			GridRangeInfoList list = dg.Selections.GetSelectedRows(true, false);
			if (list.Count == 0)
			{
				MessageBox.Show("Select a row");
				return;
			}

			GridRangeInfo range = list[0];
			int row = range.Top;
			string location = dg[row, 1].Text;


			ShowLocationContentsDlg sld = new ShowLocationContentsDlg(location);
			sld.Owner = this;
			sld.Show();

		}

		private void btnGet_Click(object sender, System.EventArgs e)
		{
			GetLocations();
		}

		private void cboTest_SelectedIndexChanged(object sender, System.EventArgs e)
		{
			if (_isInit)
				return;
			_test = (int)cboTest.SelectedValue;
		}

		private void cboProtocol_SelectedIndexChanged(object sender, System.EventArgs e)
		{
			if (_isInit)
				return;
			_protocol = (int)cboProtocol.SelectedValue;
		}

	}

	public class SelectLocationEventArgs
	{
		public int SelectType = 0;
		public string Location = "";

		public SelectLocationEventArgs()
		{

		}
	}
}
